package study.intconsulting.net.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

public class HongClass {
	
	private Socket socket;
	private final int timeout = 1000; 

	public String call(String reqXml){
		String serverName = "localhost";
		int port = 9999;
		String str = null;
		try{
			Socket socket = openSocket(serverName, port, 10);
			
			System.out.println("======================== HongClass.java reqXML : "+reqXml.length());
			
			str = reqXml.length()+"\n"+reqXml;

			System.out.println("======================== HongClass.java str : "+str);
			writeToServer(socket, str);
			str = readFromServer(socket);
			socket.close();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			if(socket != null){
				try {
					socket.close();
				} catch (IOException ie) {
					// TODO Auto-generated catch block
					ie.printStackTrace();
				}
			}
		}
		return str;
	}

	public Socket openSocket(String server, int port, int time) throws Exception{
		// socket 생성
		try{
			InetAddress inetAddress = InetAddress.getByName(server);
			SocketAddress socketAddress = new InetSocketAddress(inetAddress,port);
			socket = new Socket();
			socket.connect(socketAddress, timeout * time);
			return socket;
		}catch (SocketTimeoutException ste){
			ste.printStackTrace();
			throw ste;
		}
	}

	public void writeToServer(Socket socket, String writeTo){

		try{
			BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			
			bufferedWriter.write(writeTo + '\n');
			bufferedWriter.flush();
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public String readFromServer(Socket socket){
		try{
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String str;

			while((str = bufferedReader.readLine()) != null){
				sb.append(str);
			}

			bufferedReader.close();
			return sb.toString();

		}catch (IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args){
		// TODO Auto-generated method stub
		String reqXml = "<message><who>who</who></message>";
		HongClass hongClass = new HongClass();
		String resXml = hongClass.call(reqXml);
		System.out.println("result : " + resXml);
	}
}
